<?php

namespace Smjt\Cart;

use Illuminate\Support\Facades\Redis;

class Cart
{
    protected $redis;

    public function __construct()
    {
        $this->redis = Redis::connection();
    }

    protected function getCartKey($userId)
    {
        return config('projectcart.project_cart_prefix') . "-cart:{$userId}";
    }

    /**
     * @description 加入购物车及数量操作
     * @user WSC
     * @date 2024/8/17
     * @time 14:42
     * @param $userId
     * @param $item
     * @return false
     */
    public function add($userId, $item)
    {
        $cartKey = $this->getCartKey($userId);
        $get = $this->redis->hget($cartKey, $item['id']);
        if ($get) {
            $get = json_decode($get, true);
            //如果小于等于0，则删除
            if ($get['num'] + $item['num'] <= 0) {
                return $this->delete($userId, $item['id']);
            } else {
                //大于0
                $item['num'] = $get['num'] + $item['num'];
            }
        }
        try {
            return $this->redis->hset($cartKey, $item['id'], json_encode($item));
        } catch (\Exception $e) {
            return FALSE;
        }
    }

    /**
     * @description 删除以及批量删除功能
     * @user WSC
     * @date 2024/8/17
     * @time 14:42
     * @param $userId
     * @param $itemId
     * @return mixed
     */
    public function delete($userId, $itemId)
    {
        $cartKey = $this->getCartKey($userId);
        $itemIds = explode(',', $itemId);
        foreach ($itemIds as $k => $v) {
            $res = $this->redis->hdel($cartKey, $v);
        }
        return $res;

    }

    /**
     * @description 获取购物车列表
     * @user WSC
     * @date 2024/8/17
     * @time 15:09
     * @param $userId
     * @return array
     */
    public function get($userId)
    {
        $cartKey = $this->getCartKey($userId);
        $items = $this->redis->hgetall($cartKey);

        return array_map(function ($item) {
            return json_decode($item, true);
        }, $items);
    }

    /**
     * @description 删除整个用户的hash数据
     * @user WSC
     * @date 2024/8/19
     * @time 9:07
     * @param $userId
     * @return mixed
     */
    public function remove($userId)
    {
        $cartKey = $this->getCartKey($userId);
        return $this->redis->delete($cartKey);
    }
}
